{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### clone代码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!git clone https://github.com/modelscope/modelscope-agent.git"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 安装特定依赖"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!cd modelscope-agent && !pip install -r requirements.txt"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 本地配置"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.chdir('modelscope-agent/examples/tools')\n",
    "\n",
    "import sys\n",
    "sys.path.append('../../')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### API_KEY管理"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 本示例使用的是DashScope灵积模型服务，开通灵积模型服务后，单个账号（含子账号）对每个模型提供首次使用500张图像生成免费额度，有效期180天。\n",
    "- 开通服务并获得API-KEY：[开通DashScope并创建API-KEY](https://help.aliyun.com/zh/dashscope/developer-reference/activate-dashscope-and-create-an-api-key?spm=a2c4g.11186623.0.i21)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "print('请输入DASHSCOPE_API_KEY')\n",
    "os.environ['DASHSCOPE_API_KEY'] = input()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 设置openapi schema"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "schema_openAPI = {\n",
    "    \"schema\": {\n",
    "        \"openapi\":\"3.1.0\",\n",
    "        \"info\":{\n",
    "            \"title\":\"wanx-v1 Generation API\",\n",
    "            \"description\":\"API for generating image with wanx-v1\",\n",
    "            \"version\":\"v1.0.0\"\n",
    "        },\n",
    "        \"servers\":[\n",
    "            {\n",
    "                \"url\":\"https://dashscope.aliyuncs.com\"\n",
    "            }\n",
    "        ],\n",
    "        \"paths\":{\n",
    "            \"/api/v1/services/aigc/text2image/image-synthesis\":{\n",
    "                \"post\":{\n",
    "                    \"summary\":\"wanx-v1 text2image\",\n",
    "                    \"operationId\":\"wanx_v1_text2image\",\n",
    "                    \"tags\":[\n",
    "                        \"wanx-v1 text2image\"\n",
    "                    ],\n",
    "                    \"requestBody\":{\n",
    "                        \"required\":True,\n",
    "                        \"X-DashScope-Async\":\"enable\",\n",
    "                        \"content\":{\n",
    "                            \"application/json\":{\n",
    "                                \"schema\":{\n",
    "                                    \"$ref\":\"#/components/schemas/wanx_v1_text2imageRequest\"\n",
    "                                }\n",
    "                            }\n",
    "                        }\n",
    "                    },\n",
    "                    \"responses\":{\n",
    "                        \"200\":{\n",
    "                            \"description\":\"Successful Response\",\n",
    "                            \"content\":{\n",
    "                                \"application/json\":{\n",
    "                                    \"schema\":{\n",
    "                                        \"$ref\":\"#/components/schemas/wanx_v1_text2imageResponse\"\n",
    "                                    }\n",
    "                                }\n",
    "                            }\n",
    "                        }\n",
    "                    },\n",
    "                    \"security\":[\n",
    "                        {\n",
    "                            \"BearerAuth\":[]\n",
    "                        }\n",
    "                    ]\n",
    "                }\n",
    "            },\n",
    "            \"/api/v1/tasks/{task_id}\":{\n",
    "                \"get\":{\n",
    "                    \"summary\":\"Get Text2image Result\",\n",
    "                    \"operationId\":\"gettext2imageresult\",\n",
    "                    \"tags\":[\n",
    "                        \"Get Result\"\n",
    "                    ],\n",
    "                    \"parameters\":[\n",
    "                        {\n",
    "                            \"name\":\"task_id\",\n",
    "                            \"in\":\"path\",\n",
    "                            \"required\":True,\n",
    "                            \"description\":\"The unique identifier of the Text2image generation task\",\n",
    "                            \"schema\":{\n",
    "                                \"type\":\"string\"\n",
    "                            }\n",
    "                        }\n",
    "                    ],\n",
    "                    \"security\":[\n",
    "                        {\n",
    "                            \"BearerAuth\":[]\n",
    "                        }\n",
    "                    ]\n",
    "                }\n",
    "            }\n",
    "        },\n",
    "        \"components\":{\n",
    "            \"schemas\":{\n",
    "                \"wanx_v1_text2imageRequest\":{\n",
    "                    \"type\":\"object\",\n",
    "                     \"properties\":{\n",
    "                        \"model\":{\n",
    "                            \"type\":\"string\",\n",
    "                            \"enum\":[\n",
    "                                \"wanx-v1\"\n",
    "                            ]\n",
    "                        },\n",
    "                        \"input\":{\n",
    "                            \"type\":\"object\",\n",
    "                            \"properties\":{\n",
    "                                \"prompt\":{\n",
    "                                    \"type\":\"string\",\n",
    "                                    \"example\":\"高清的,大师级的,4K,正面\",\n",
    "                                    \"description\":\"描述画面的提示词信息\",\n",
    "                                    \"required\": True\n",
    "                                }\n",
    "                            }\n",
    "                        },\n",
    "                        \"parameters\":{\n",
    "                            \"type\":\"object\",\n",
    "                            \"properties\":{\n",
    "                                \"style\":{\n",
    "                                    \"type\":\"string\",\n",
    "                                    \"example\":\"<anime>\",\n",
    "                                    \"description\":\"输出图像的风格\",\n",
    "                                    \"required\": True,\n",
    "                                    \"enum\":[\n",
    "                                        \"<auto>\",\n",
    "                                        \"<3d cartoon>\",\n",
    "                                        \"<anime>\",\n",
    "                                        \"<oil painting>\",\n",
    "                                        \"<watercolor>\",\n",
    "                                        \"<sketch>\",\n",
    "                                        \"<chinese painting>\",\n",
    "                                        \"<flat illustration>\"\n",
    "                                    ]\n",
    "                                },\n",
    "                                \"size\":{\n",
    "                                    \"type\":\"string\",\n",
    "                                    \"example\":\"1024*1024\",\n",
    "                                    \"description\":\"生成图像的分辨率,默认为1024*1024像素\",\n",
    "                                    \"required\":True,\n",
    "                                    \"enum\":[\n",
    "                                        \"1024*1024\",\n",
    "                                        \"720*1280\",\n",
    "                                        \"1280*720\"\n",
    "                                    ]\n",
    "                                },\n",
    "                                \"n\":{\n",
    "                                    \"type\":\"integer\",\n",
    "                                    \"example\":1,\n",
    "                                    \"description\":\"本次请求生成的图片数量\",\n",
    "                                    \"required\":True\n",
    "                                },\n",
    "                                \"seed\":{\n",
    "                                    \"type\":\"integer\",\n",
    "                                    \"example\":42,\n",
    "                                    \"description\":\"图片生成时候的种子值，取值范围为(0,4294967290)\",\n",
    "                                    \"required\":True\n",
    "                                }\n",
    "                            }\n",
    "                        }\n",
    "                    },\n",
    "                    \"required\":[\n",
    "                        \"model\",\n",
    "                        \"input\",\n",
    "                        \"parameters\"\n",
    "                    ]\n",
    "                },\n",
    "                \"wanx_v1_text2imageResponse\":{\n",
    "                    \"type\":\"object\",\n",
    "                    \"properties\":{\n",
    "                        \"output\":{\n",
    "                            \"type\":\"string\",\n",
    "                            \"description\":\"Generated image URL or data.\"\n",
    "                        }\n",
    "                    }\n",
    "                }\n",
    "            },\n",
    "            \"securitySchemes\":{\n",
    "                \"ApiKeyAuth\":{\n",
    "                    \"type\":\"apiKey\",\n",
    "                    \"in\":\"header\",\n",
    "                    \"name\":\"Authorization\"\n",
    "                }\n",
    "            }\n",
    "        }\n",
    "    },\n",
    "\"auth\": {\n",
    "    \"type\": \"API Key\",\n",
    "    \"apikey\": \"\", # 这里填入API key\n",
    "    \"apikey_type\": \"Bearer\"\n",
    "  },\n",
    "\"privacy_policy\": \"\"\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 构建tool"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import copy\n",
    "from modelscope_agent.tools.base import OpenapiServiceProxy\n",
    "from modelscope_agent.tools.base import TOOL_REGISTRY\n",
    "\n",
    "openapi_instance = OpenapiServiceProxy(openapi=schema_openAPI['schema'])\n",
    "schema_info = copy.deepcopy(openapi_instance.api_info_dict)\n",
    "for item in schema_info:\n",
    "        schema_info[item].pop('is_active')\n",
    "        schema_info[item].pop('is_remote_tool')\n",
    "        schema_info[item].pop('details')\n",
    "print(schema_info)\n",
    "print(openapi_instance.api_info_dict)\n",
    "function_list = []\n",
    "tool_names = openapi_instance.tool_names\n",
    "for tool_name in tool_names:\n",
    "    openapi_instance_for_specific_tool = copy.deepcopy(openapi_instance)\n",
    "    openapi_instance_for_specific_tool.name = tool_name\n",
    "    function_plain_text = openapi_instance_for_specific_tool.parser_function_by_tool_name(\n",
    "        tool_name)\n",
    "    openapi_instance_for_specific_tool.function_plain_text = function_plain_text\n",
    "    TOOL_REGISTRY[tool_name] = openapi_instance_for_specific_tool\n",
    "    function_list.append(tool_name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 构建agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from modelscope_agent.agents import RolePlay\n",
    "\n",
    "role_template = '你扮演哆啦A梦小画家,你需要根据用户的要求用哆啦A梦的语气满足他们'\n",
    "llm_config = {\n",
    "    'model': 'qwen-max',\n",
    "    'model_server': 'dashscope',\n",
    "    }\n",
    "kwargs = {}\n",
    "kwargs[\"credentials\"] =                 \\\n",
    "{\n",
    "    \"auth_type\": \"api_key\",\n",
    "    \"api_key_header\": \"Authorization\",\n",
    "    \"api_key_value\": \"\", # 这里填入API key\n",
    "}\n",
    "\n",
    "bot = RolePlay(function_list=function_list,llm=llm_config, instruction=role_template)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 执行agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "response = bot.run(\"哆啦A梦！帮我画一幅可爱的小女孩的照片\", remote=False, print_info=True, **kwargs)\n",
    "text = ''\n",
    "for chunk in response:\n",
    "    text += chunk\n",
    "print(text)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "modelscope",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
